
import tkinter as tk
import random
import json
from datetime import date

SCORE_FILE = "score.json"

class MultiplicationGame:
    def __init__(self, root):
        self.root = root
        self.root.title("乘法口诀练习")
        self.root.geometry("600x550") # Increased height for new label

        # --- Game State Variables ---
        self.daily_correct_answers = 0
        self.total_correct_answers = 0
        self.coins = 0
        self.session_score = 0
        self.timer_seconds = 180  # 3 minutes

        self.load_game_data()

        # --- UI Elements ---
        # Score and Coins Display
        self.stats_frame = tk.Frame(root)
        self.stats_frame.pack(pady=10)
        self.coin_label = tk.Label(self.stats_frame, text=f"金币: {self.coins}", font=("Helvetica", 16, "bold"), fg="gold")
        self.coin_label.pack(side=tk.LEFT, padx=20)
        self.daily_score_label = tk.Label(self.stats_frame, text=f"今日答对: {self.daily_correct_answers}", font=("Helvetica", 16))
        self.daily_score_label.pack(side=tk.LEFT, padx=20)

        self.timer_label = tk.Label(root, text="", font=("Helvetica", 20))
        self.timer_label.pack(pady=10)

        self.question_label = tk.Label(root, text="点击开始按钮进行挑战", font=("Helvetica", 36))
        self.question_label.pack(pady=20)

        self.feedback_label = tk.Label(root, text="", font=("Helvetica", 20))
        self.feedback_label.pack(pady=10)

        self.options_frame = tk.Frame(root)
        self.options_frame.pack(pady=20)

        self.option_buttons = []
        for i in range(4):
            button = tk.Button(self.options_frame, text="", font=("Helvetica", 24), width=5, command=lambda i=i: self.check_answer(i))
            button.grid(row=0, column=i, padx=10)
            self.option_buttons.append(button)
            button.config(state=tk.DISABLED)

        self.start_button = tk.Button(root, text="开始游戏", font=("Helvetica", 20), command=self.start_game)
        self.start_button.pack(pady=20)

    def load_game_data(self):
        try:
            with open(SCORE_FILE, 'r') as f:
                data = json.load(f)
                self.total_correct_answers = data.get("total_correct_answers", 0)
                
                today = str(date.today())
                if data.get("last_played_date") == today:
                    self.daily_correct_answers = data.get("daily_correct_answers", 0)
                else:
                    self.daily_correct_answers = 0 # Reset for new day
        except (FileNotFoundError, json.JSONDecodeError):
            # If file doesn't exist or is empty, all scores are 0
            self.total_correct_answers = 0
            self.daily_correct_answers = 0
        
        # Calculate coins based on total correct answers
        self.coins = (self.total_correct_answers // 50) * 2

    def save_game_data(self):
        today = str(date.today())
        data = {
            "last_played_date": today,
            "daily_correct_answers": self.daily_correct_answers,
            "total_correct_answers": self.total_correct_answers
        }
        with open(SCORE_FILE, 'w') as f:
            json.dump(data, f)

    def start_game(self):
        self.session_score = 0
        self.timer_seconds = 180
        self.start_button.config(state=tk.DISABLED)
        self.update_ui_labels()
        self.update_timer()
        self.next_question()
        for button in self.option_buttons:
            button.config(state=tk.NORMAL)

    def update_timer(self):
        if self.timer_seconds > 0:
            minutes = self.timer_seconds // 60
            seconds = self.timer_seconds % 60
            self.timer_label.config(text=f"剩余时间: {minutes:02d}:{seconds:02d}")
            self.timer_seconds -= 1
            self.root.after(1000, self.update_timer)
        else:
            self.end_game()

    def end_game(self):
        self.timer_label.config(text="时间到!")
        self.question_label.config(text=f"本次答对: {self.session_score} 题")
        self.feedback_label.config(text="")
        for button in self.option_buttons:
            button.config(state=tk.DISABLED)
        self.start_button.config(state=tk.NORMAL)
        self.save_game_data() # Save at the end of a session

    def next_question(self):
        self.feedback_label.config(text="")
        for button in self.option_buttons:
            button.config(state=tk.NORMAL, bg="SystemButtonFace")

        self.num1 = random.randint(1, 9)
        self.num2 = random.randint(1, 9)
        self.correct_answer = self.num1 * self.num2
        self.question_label.config(text=f"{self.num1} x {self.num2} = ?")

        options = self.generate_options()
        self.correct_option_index = options.index(self.correct_answer)

        for i in range(4):
            self.option_buttons[i].config(text=str(options[i]))

    def generate_options(self):
        options = {self.correct_answer}
        while len(options) < 4:
            wrong_answer = random.randint(1, 81)
            if wrong_answer != self.correct_answer:
                options.add(wrong_answer)
        
        options_list = list(options)
        random.shuffle(options_list)
        return options_list

    def check_answer(self, index):
        if self.timer_seconds <= 0:
            return

        chosen_answer = int(self.option_buttons[index].cget("text"))
        
        for button in self.option_buttons:
            button.config(state=tk.DISABLED)

        if chosen_answer == self.correct_answer:
            self.session_score += 1
            self.daily_correct_answers += 1
            
            old_coins = self.coins
            self.total_correct_answers += 1
            self.coins = (self.total_correct_answers // 50) * 2

            if self.coins > old_coins:
                self.feedback_label.config(text="太棒了! 获得2个金币!", fg="orange")
            else:
                self.feedback_label.config(text="正确!", fg="green")

            self.option_buttons[index].config(bg="green")
            self.save_game_data() # Save progress immediately
        else:
            self.feedback_label.config(text=f"错误! 正确答案是: {self.correct_answer}", fg="red")
            self.option_buttons[index].config(bg="red")
            self.option_buttons[self.correct_option_index].config(bg="lightgreen")

        self.update_ui_labels()
        if self.timer_seconds > 0:
            self.root.after(2000, self.next_question)

    def update_ui_labels(self):
        self.coin_label.config(text=f"金币: {self.coins}")
        self.daily_score_label.config(text=f"今日答对: {self.daily_correct_answers}")

if __name__ == "__main__":
    root = tk.Tk()
    game = MultiplicationGame(root)
    root.mainloop()
